package com.dongdongshop.serviceimpl;

import com.dongdongshop.mapper.TbSpecificationMapper;
import com.dongdongshop.mapper.TbSpecificationOptionMapper;
import com.dongdongshop.pojo.TbSpecification;
import com.dongdongshop.pojo.TbSpecificationOption;
import com.dongdongshop.pojo.TbSpecificationOptionExample;
import com.dongdongshop.service.SpecificationOptionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@com.alibaba.dubbo.config.annotation.Service
public class SpecificationOptionServiceImpl implements SpecificationOptionService {
    @Autowired
    private TbSpecificationMapper tbSpecificationMapper;
    @Autowired
    private TbSpecificationOptionMapper tbSpecificationOptionMapper;

    //规格增加
    @Override
    @Transactional
    public Boolean insertSpec(TbSpecification tbSpecification, List<TbSpecificationOption> tbSpecificationOptions) {
        try {
            //增加规格名称并返回id
            tbSpecificationMapper.insertReturnId(tbSpecification);
            Long id = tbSpecification.getId();
            for (int i = 0; i < tbSpecificationOptions.size(); i++) {
                //将id放入规格选项类
                tbSpecificationOptions.get(i).setSpecId(id);
                tbSpecificationOptionMapper.insert(tbSpecificationOptions.get(i));
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    //查询规格选项
    @Override
    public List<TbSpecificationOption> selectOptionBySpecid(Long id) {
        TbSpecificationOptionExample toe = new TbSpecificationOptionExample();
        TbSpecificationOptionExample.Criteria criteria = toe.createCriteria();
        criteria.andSpecIdEqualTo(id);
        List<TbSpecificationOption> tbSpecificationOptions = tbSpecificationOptionMapper.selectByExample(toe);
        return tbSpecificationOptions;
    }

    //修改
    @Override
    public Boolean updateSpec(TbSpecification tbSpecification, List<TbSpecificationOption> tbSpecificationOptions) {
        try {
            //修改规格
            tbSpecificationMapper.updateByPrimaryKeySelective(tbSpecification);
            //修改规格选项
            for (int i = 0; i < tbSpecificationOptions.size(); i++) {
                tbSpecificationOptionMapper.updateByPrimaryKeySelective(tbSpecificationOptions.get(i));
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
}
